#ifndef SPIDER_H_
#define SPIDER_H_

#include <iostream>
#include <string>
#include <uv.h>
#include "define.h"
#include "spidermessage.h"

enum SpiderStatus
{
    SPIDER_STATUS_INIT = 0x01,
    SPIDER_STATUS_RUN = 0x02,
};

class Spider
{
private:
    Spider() = default;
    ~Spider() = default;
    // 删除拷贝构造函数和赋值运算符，‌防止拷贝
    Spider(const Spider &) = delete;
    Spider &operator=(const Spider &) = delete;

public:
    uint64_t m_interval;
    uint64_t m_lastTick;
    uint64_t m_lastRecvTick;
    uint8_t m_status;
    uv_loop_t *m_loop;

    uv_tcp_t m_eagleTcp;
    uv_timer_t m_spiderTimer;
    uv_thread_t m_tid;
    uv_getaddrinfo_t m_resolver;
    struct sockaddr m_eagleAddr;
    uint32_t m_sendLen;
    char m_sendBuf[TCP_BUFF_SIZE];
    uint32_t m_recvLen;
    char m_recvBuf[TCP_BUFF_SIZE];

    int m_commandTimeout;
    int m_idleTimeout;

    static Spider &GetInstance();
    bool Start();
    void Stop();

    uv_loop_t *GetLoop()
    {
        return m_loop;
    };
    void OnSpiderCheck();
    void RunLoop();

    void HandReaddata(ssize_t nread);

    bool DoGetEagleAddr();
    void DoConnectEagle(struct sockaddr *target);
    void DoRegister();
    bool DoRegisterResp(MessageRegisterResp *resp);
    void DoHeartbeatResp(MessageHeartbeat *resp);
    bool DoTcpReq(MessageTcp *req);
    bool DoUdpReq(MessageUdp *req);

    void Close();

    bool DoSendHeartbeat();
    void DoSendToEagle();
};

#endif